package com.jd.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.jd.basic.dto.LoginDto;
import com.jd.basic.exception.BusinessException;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.RsaUtils;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.HttpUtil;
import com.jd.sys.domain.Menu;
import com.jd.user.constant.WxConstants;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.domain.Wxuser;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.mapper.WxuserMapper;
import com.jd.user.service.ILogininfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public AjaxResult accountLogin(LoginDto loginDto) { // 账号登录
        // 空值判断
        if (StrUtil.isBlank(loginDto.getAccount()) || StrUtil.isBlank(loginDto.getPassword())) {
            throw new BusinessException("信息不能为空！");
        }
        // 用户是否存在
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("该用户不存在！");
        }
        // 密码是否正确
        String salt = logininfo.getSalt(); // 获取盐值
        if (!logininfo.getPassword().equals(SecureUtil.md5(loginDto.getPassword() + salt))) {
            throw new BusinessException("密码错误！");
        }
        // 是否启用
        if (!logininfo.getDisable()) {
            throw new BusinessException("该用户未启用！");
        }
        // 封装map传递用户信息
//        String token = UUID.randomUUID().toString(); // 获取token 作为key
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES); // 存到redis设置过期时间
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        // 设置盐值和密码为空在给前端
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        map.put("logininfo", logininfo);
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(map);
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) { // 微信登陆
        // 想办法发送第二个请求，通过API文档，需要对响应的数据做处理 通过code获取access_token的接口。
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code")); // 获取url
        // 发http请求
        String jsonStr = HttpUtil.httpGet(url);
        // 通过工具类将json字符转成对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        // 获取token和openid
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        // 通过openid判断有无wx用户
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if (wxuser != null) { // wxuser有信息 判断user表有无
            User user = userMapper.findOne(wxuser.getUserId());
            if (user != null) { // user信息也有 直接绵密登录
                // 封装map传递用户信息
                Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
//                String token = UUID.randomUUID().toString(); // 获取token 作为key
//                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES); // 存到redis设置过期时间
//                Map<String, Object> resultMap = new HashMap<>();
//                resultMap.put("token", token);
//                // 设置盐值和密码为空在给前端
//                logininfo.setPassword(null);
//                logininfo.setSalt(null);
//                resultMap.put("logininfo", logininfo);
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(resultMap);
            }
        }
        // 走这里代表需要跳转到绑定页面
        // 这里直接将token和openid响应给前端，用来第三次请求
        String params = "?access_token=" + accessToken + "&openid=" + openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) { // 微信扫码绑定
        // 参数校验
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openid = map.get("openid");
        // 手机和验证码空值校验
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(verifyCode)) {
            throw new BusinessException("信息不能为空！");
        }
        // 验证码校验是否过期
        Object phoneCodeObj = redisTemplate.opsForValue().get("binder:" + phone);
        if (phoneCodeObj == null) {
            throw new BusinessException("手机验证码已过期！");
        }
        // 验证码是否错误
        if (!verifyCode.equals(phoneCodeObj.toString().split(":")[0])) {
            throw new BusinessException("手机验证码错误！");
        }
        // 获取user对象以及logininfo
        User user = userMapper.findByPhone(phone);
        if (user == null) {
            user = phone2User(phone); // 通过phone创建user对象
            Logininfo logininfo = new Logininfo(); // 创建logininfo对象
            BeanUtils.copyProperties(user, logininfo); // 将数据赋值给logininfo
            logininfo.setDisable(true); // 启用
            logininfo.setType(1); // 用户
            logininfoMapper.add(logininfo); // 自增长id
            user.setLogininfoId(logininfo.getId()); // 设置loginid
            userMapper.add(user);
        }
        // 获取wxuser对象
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if (wxuser == null) { // 这里需要发第三个请求获取对象
            String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN",accessToken)
                    .replace("OPENID",openid);
            // 发请求
            String jsonStr = HttpUtil.httpGet(url); // json字符串
            wxuser = jsonStr2WxUser(jsonStr); // 通过方法赋值对象
            wxuserMapper.add(wxuser);
        }
        // 如果userid不对找不到，直接重新绑定
        wxuser.setUserId(user.getId());
        wxuserMapper.update(wxuser);
        // 绑定完免密登录
        // 封装map传递用户信息
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
//        String token = UUID.randomUUID().toString(); // 获取token 作为key
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES); // 存到redis设置过期时间
//        Map<String, Object> resultMap = new HashMap<>();
//        map.put("token", token);
//        // 设置盐值和密码为空在给前端
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        resultMap.put("logininfo", logininfo);
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(resultMap);
    }



    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        String nickname = jsonObject.getString("nickname");
        String openid = jsonObject.getString("openid");
        String headimgurl = jsonObject.getString("headimgurl");
        String unionid = jsonObject.getString("unionid");
        wxuser.setNickname(nickname);
        wxuser.setOpenid(openid);
        wxuser.setHeadimgurl(headimgurl);
        wxuser.setUnionid(unionid);
        return wxuser;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = RandomUtil.randomString(32);
        String password = RandomUtil.randomString(8);
        String md5 = SecureUtil.md5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        user.setState(1);
        return user;
    }

    @Override
    public Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        // 要加密登录信息，如果是管理员，还需要当前登陆人的权限和菜单 - loginData
        // 要向前端传递数据，jwtToken 前端没有解密，logininfo对象-显示用户信息
        // 菜单 - 动态菜单，权限 - 按钮权限
        LoginData loginData = new LoginData();
        HashMap<String, Object> map = new HashMap<>();
        loginData.setLogininfo(logininfo);
        map.put("logininfo",logininfo);
        // 如果是管理员，还要传递权限和菜单
        if (logininfo.getType() == 0){
            // 查询当前登陆人的权限，资源权限只需要t_permission的sn
            List<String> permissions = logininfoMapper.findPermission(logininfo.getId());
            loginData.setPermissions(permissions);
            map.put("permissions",permissions);
            // 查询当前登陆人的菜单，菜单权限需要t_menu的name,component,url,icon,parent_id
            List<Menu> menus = logininfoMapper.findMenus(logininfo.getId());
            loginData.setMenus(menus);
            map.put("menus",menus);
        }
        // 获取私钥加密 - jwtToken - map
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
